package com.xbongbong.saas.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import org.apache.commons.collections4.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @author 吴峰
 * @date 2022/03/17 17:11
 */
public class OrganizationFieldUtil {

    public static void getUserAndDeptField(List<FieldAttrEntity> explainList, Set<String> userSet, Set<String> departmentSet) {
        for (FieldAttrEntity item : explainList) {
            Integer fieldType = item.getFieldType();
            if (ExplainUtil.isUser(fieldType)) {
                userSet.add(item.getAttr());
            }
            if (ExplainUtil.isDept(fieldType)) {
                departmentSet.add(item.getAttr());
            }
        }
    }

    public static Set<String> getUserId(JSONObject data, Set<String> userSet) {
        Set<String> userIdSet = new HashSet<>();
        if (CollectionUtils.isEmpty(userSet)) {
            return userIdSet;
        }
        userSet.forEach(item->{
            if (data.get(item) instanceof String && StringUtil.isNotEmpty(data.getString(item))) {
                userIdSet.add(data.getString(item));
            } else if (data.get(item) instanceof List) {
                List<String> userIdArray = JSONArray.parseArray(JSON.toJSONString(data.get(item)), String.class);
                if ( CollectionsUtil.isNotEmpty(userIdArray) ) {
                    userIdSet.addAll(userIdArray);
                }
            }

        });
        return userIdSet;
    }

    public static Set<Long> getDeptId(JSONObject data, Set<String> deptSet) {
        Set<Long> deptIdSet = new HashSet<>();
        if (CollectionUtils.isEmpty(deptSet)) {
            return deptIdSet;
        }
        deptSet.forEach(item->{
            if (data.get(item) instanceof Long && !Objects.equals(0L, data.getLong(item))) {
                deptIdSet.add(data.getLong(item));
            }else if (data.get(item) instanceof List) {
                List<Long> userIdArray = JSONArray.parseArray(JSON.toJSONString(data.get(item)), Long.class);
                if ( CollectionsUtil.isNotEmpty(userIdArray) ) {
                    deptIdSet.addAll(userIdArray);
                }
            }
        });
        return deptIdSet;
    }



}
